var http = require('http');
var fs=require('fs');
var url=require('url');
var querystring = require('querystring');
http.createServer(function (request, response) {
	response.statusCode=200;
	response.setHeader('Content-Type', 'text/html');
	var ext = request.url.substr(request.url.lastIndexOf('.')+1); //取出后缀名
	var exts ={
		'html':'text/html',
		'css':'text/css',
		'png':'image/png',
		'js':'javascript'
	}

	if(exts[ext] == null){
		exts[ext]='text/plain';
	}
	response.setHeader('Content-Type',exts[ext]);

	var data='404';
	var p=url.parse(request.url,true);//添加参数true,将query字符串解析成对象
	//console.log(p);
	var urls=p.pathname;//选取pathname进行URL判断
	if(urls=='/message.html'){
		try{
			data = fs.readFileSync('.'+ request.url,'utf8');
			item = fs.readFileSync('data.json','utf8');
			item = JSON.parse(item);
			var s="";
			for(var i=0;i<item.length;i++){
				s+='<div class="item">';
				s+='<h6>'+item[i].author+'<span>'+item[i].time+'</span></h6>';
				s+='<p>'+item[i].message+'<a href="/delmessage?id='+i+'">x</a></p>';
				s+='</div>';
		}
			data=data.replace(/%main/g,s);
		}
		catch(e){   }
	}

	else if(urls=='/form.html'){
		data = fs.readFileSync('.'+ request.url,'utf8');
		
	}

	else if(urls=='/addmessage'){
		//注释处为GET
		author=p.query.author;
		message=p.query.message;
		item = fs.readFileSync('data.json','utf8');//拿出字符串item
		item = JSON.parse(item);//item解析成对象
		item.push({//item内加入新的对象
			author:author,
			message:message,
			time:new Date()
		})
		item=JSON.stringify(item);//item由对象解析成字符串
		//console.log(item);
		fs.writeFileSync('data.json',item);//将item写入json文件中
		data="提交成功";
		response.writeHead(302,{
			'Location':'message.html'
		})
		//console.log(item);
		
	}
	else if(urls=='/delmessage'){
		id=p.query.id;
		item = fs.readFileSync('data.json','utf8');
		item = JSON.parse(item);
		item.splice(id,1);
		item=JSON.stringify(item);
		fs.writeFileSync('data.json',item);
		data="提交成功";
		response.writeHead(302,{
			'Location':'message.html'
		});
	}

	response.write(data);
	response.end();
}).listen(80);
console.log('Server running at http://127.0.0.1:80');